package demo7;

import javax.swing.tree.TreeNode;

/**
 * Created with IntelliJ IDEA.
 * Description:根据二叉树创建字符串
 * User: liangyuanzhang
 * Date: 2025-4-30
 * Time: 0:14
 */
public class Test {
    public String tree2str(TreeNode root) {
        if(root == null) {
            return null;
        }

        StringBuilder stringBuilder = new StringBuilder();//到一个存一个,效率高
        tree2strChild(root,stringBuilder);
        return stringBuilder.toString();

    }

    //这个方法没有返回值是因为已经在stringBuilder拼接完了
    public void tree2strChild(TreeNode t,StringBuilder stringBuilder) {
        if(t == null) return;
        //这里不为空就直接将根节点放到字符串里
        stringBuilder.append(t.val);

        if(t.left != null){
            //只要左边不为空直接拼接上一个小括号
            stringBuilder.append("(");
            tree2strChild(t.left,stringBuilder);
            stringBuilder.append(")");
        }else{
            if(t.right == null){
                return;
            }else{
                stringBuilder.append("()");
            }
        }

        if(t.right != null){
            stringBuilder.append("(");
            tree2strChild(t.right,stringBuilder);
            stringBuilder.append(")");
        }else{
            return;
        }
    }
}